package com.ruoyi.system.outto.goods.impl;


import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.V2.inter.mapper.SalePartnerMapper;
import com.ruoyi.system.V2.inter.mapper.SelectPushMapper;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.model.domain.SelectPush;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.game.CommonApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;


/**
 * 平台过验证码
 */

@Slf4j
@Service
public class ApiSmsService {

    @Autowired
    CommonApi commonApi;
    @Resource
    SelectPushMapper selectPushMapper;


    @Resource
    SalePartnerMapper salePartnerMapper;

    @Async
    public void toPanzhi(String msg, SalePartner salePartner) {

        String phone = salePartner.getSaleKey();
        String checkCode = "";
        if (StringUtils.isNotEmpty(msg)) {
            String[] split = msg.split("，");
            checkCode = split[0].split("验证码")[1];
        }

//        SalePartner salePartner = new SalePartner();
//        salePartner.setSaleKey(phone);
//        salePartner.setOther("aa120120");

        String token = commonApi.loginPanzhi(salePartner);

        Map<String, Object> params = new HashMap<>();
        phone = phone.replace("+86", "");
        JSONObject action = new JSONObject();
        action.put("phone", phone.replace("+86", ""));
        action.put("smsCode", checkCode);

        params.put("action", action);

        // 生成 随机数 并生成sign  注意 &2147483647         &accessKey=3qXyB7uf
        StringBuilder sb = new StringBuilder();
        long PZTimestamp = System.currentTimeMillis();
        String Random = getRanString();
        sb.append("PZTimestamp=");
        sb.append(PZTimestamp);
        sb.append("&Random=");
        sb.append(Random);
        sb.append("&2147483647=");
        sb.append(JSONObject.toJSON(params));
        sb.append("&accessKey=3qXyB7uf");
        System.out.println(sb.toString());
        String b = sb.toString();
        try {
            b = URLEncoder.encode(b, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        b = b.replace("%26", "&");
        b = b.replace("%3D", "=");
        System.out.println(b);
        b = b.replaceAll("\\(", "%28");
        b = b.replaceAll("\\)", "%29");
        b = b.replaceAll("'", "%27");
        b = b.replaceAll("\\*", "%2A");
        b = b.replaceAll("~", "%7E");
        b = b.replaceAll("!|！", "%21");
        b = b.replaceAll("\\+", "%20");
        System.out.println(b);
        String sign = DigestUtils.md5Hex(b);
        System.out.println(sign);
        //开始拼装请求
        String response = HttpRequest.post("https://api.pzds.com/api/web-client/v2/userCenter/link/phone/check").header("Accept", "application/json, text/plain, */*")
                .header("PZTimestamp", String.valueOf(PZTimestamp))
                .header("Content-Type", "application/json;charset=UTF-8")
                .header("Origin", "https://www.pzds.com")
                .header("PZPlatform", "pc")
                .header("PZVersion", "1.0.0")
                .header("PZVersionCode", "1")
                .header("Random", Random)
                .header("Referer", "https://www.pzds.com/")
                .header("sign", sign)
                .header("Token", token)
                .header("sec-ch-ua-mobile", "?0")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like " +
                        "Gecko) Chrome/123.0.0.0 Safari/537.36 Edg/123 .0.0.0")
                .body(JSONObject.toJSONString(params)).execute().body();
        System.out.println("盼之短信验证返回参数============{}" + response);
        JSONObject jsonObject = JSONObject.parseObject(response);
        Boolean success = jsonObject.getBoolean("success");
        System.out.println("盼之短信验证返回状态============{}" + success);
        if (success) {
            SelectPush selectPush = selectPushMapper.selectSelectPushByConfig(salePartner.getId().toString(), "0");
            selectPush.setType("panzhi");
            selectPushMapper.updateSelectPush(selectPush);
            System.out.println("盼之短信验证成功，重启定时任务===");
        }
    }

    public static String getRanString() {
        Random random = new Random();
        //把随机生成的数字转成字符串
        String str = String.valueOf(random.nextInt(9));
        for (int i = 0; i < 5; i++) {
            str += random.nextInt(9);
        }
        if (str.startsWith("0")) {
            str = str.replaceFirst("0", "1");
        }
        return str;
    }
}
